<template>
  <div class="xtx-goods-page" v-if="goods">
    <div class="container">
      <!-- 面包屑 -->
      <XtxBread>
        <XtxBreadItem to="/">首页</XtxBreadItem>
        <XtxBreadItem :to="`/category/${goods.categories[1].id}`">{{
          goods.categories[1].name
        }}</XtxBreadItem>
        <XtxBreadItem :to="`/category/sub/${goods.categories[0].id}`">{{
          goods.categories[0].name
        }}</XtxBreadItem>
        <XtxBreadItem>{{ goods.name }}</XtxBreadItem>
      </XtxBread>
      <!-- 商品信息 -->
      <div class="goods-info">
        <div class="media">
          <GoodsImage :images="goods.mainPictures" />
          <!-- 商品销售属性组件 -->
          <GoodsSales />
        </div>
        <div class="spec">
          <!-- 商品名称信息组件 -->
          <GoodsName :goods="goods" />

          <!-- 规格组件 -->
          <!-- <GoodsSku :goods="goods" skuId="300073067"/> 测试选中 -->
          <GoodsSku :goods="goods" @change="changeSku" />

          <!-- 数量选择组件 -->
          <XtxNumbox label="数量" v-model="num" :max="goods.inventory" />

          <!-- 按钮组件(购物车) -->
          <XtxButton
            @click="insertCart()"
            type="primary"
            style="margin-top: 20px"
            >加入购物车</XtxButton
          >
        </div>
      </div>
      <!-- 商品推荐 -->
      <GoodsRelevant :goodsId="goods.id" />
      <!-- 商品详情 -->
      <div class="goods-footer">
        <div class="goods-article">
          <!-- 商品+评价 -->
          <GoodsTabs :goods="goods" />
          <!-- 注意事项 -->
          <GoodsWarn />
        </div>
        <!-- 24热榜+专题推荐 -->
        <div class="goods-aside">
          <GoodsHot :goodsId="goods.id" :type="1" />
          <GoodsHot :goodsId="goods.id" :type="2" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import GoodsImage from "./components/goods-image.vue";
import GoodsRelevant from "./components/goods-relevant";
import GoodsSales from "./components/goods-sales";
import GoodsName from "./components/goods-name";
import GoodsSku from "./components/goods-sku";
import GoodsTabs from "./components/goods-tabs";
import GoodsHot from "./components/goods-hot";
import GoodsWarn from "./components/goods-warn";
import { nextTick, ref, watch, provide } from "vue";
import { findGoods } from "@/api/product";
import { useRoute } from "vue-router";
import { useStore } from "vuex";
// 方法1
// import Message from '@/components/library/Message'
// 方法2 vue3 getCurrentInstance 方法
import {getCurrentInstance} from 'vue'

export default {
  name: "XtxGoodsPage",
  components: {
    GoodsRelevant,
    GoodsImage,
    GoodsSales,
    GoodsName,
    GoodsSku,
    GoodsTabs,
    GoodsHot,
    GoodsWarn,
  },
  setup() {
    //   1.获取商品详情,进行渲染
    const goods = useGoods();

    const changeSku = (sku) => {
      // console.log(sku);
      // 修改商品的现价原价库存信息
      if (sku.skuId) {
        goods.value.price = sku.price;
        goods.value.oldPrice = sku.oldPrice;
        goods.value.inventory = sku.inventory;
      }
      // 记录选择后的sku,可能有数据，可能没有数据{}(没有选择完整)
      currSku.value = sku;
    };

    // 提供goods数据给后代组件使用
    // 提供goods数据，子孙组件注入goods数据，渲染展示即可
    provide("goods", goods);

    // 选择的数量
    const num = ref(1);

    // 加入购物车逻辑
    // 记录sku(规格)
    const currSku = ref(null);
    // const instance = getCurrentInstance();
    const store = useStore();

    // 方法2 通过 getCurrentInstance 方法 获取当前组件实例
    // const instance=getCurrentInstance()
    // console.log(instance);
    const {proxy}=getCurrentInstance()


    const insertCart = () => {
      // 如果选择完整
      if (currSku.value && currSku.value.skuId) {
        // 方法1
        // store
        //   .dispatch("cart/insertCart", {
        //     id: goods.value.id,
        //     skuId: currSku.value.skuId,
        //     name: goods.value.name,
        //     picture: goods.value.mainPictures[0],
        //     price: currSku.value.price,
        //     nowPrice: currSku.value.price,
        //     count: num.value,
        //     attrsText: currSku.value.specsText,
        //     selected: true,
        //     isEffective: true,
        //     stock: currSku.value.inventory,
        //   })
        // 方法2
        const {skuId,price,specsText:attrsText,inventory:stock}=currSku.value
        const {id,name,mainPictures}=goods.value
        console.log(mainPictures);
        store
          .dispatch("cart/insertCart", {
            id,
            skuId,
            name,
            picture:mainPictures[0],
            price,
            nowPrice: price,
            count: num.value,
            attrsText,
            selected: true,
            isEffective: true,
            stock,
          })
          .then(() => {
            // 方法1
            // return  Message({ type:'success' ,text: "加入购物车成功" });
            // 方法2
            return proxy.$message({ type:'success' ,text: "加入购物车成功" });
          });
      } else {
        // 方法1
        // return Message({ text: "请选择完整规格" });
        // 方法2
        return proxy.$message({ text: "请选择完整规格" });
      }
    };

    return { goods, changeSku, num, insertCart };
  },
};
// 获取商品详情（包装成函数）
const useGoods = () => {
  // 出现路由地址商品ID发生变化，但是不会重新初始化组件
  const goods = ref(null);
  const route = useRoute();
  watch(
    () => route.params.id,
    (newVal) => {
      if (newVal && `/product/${newVal}` === route.path) {
        findGoods(route.params.id).then((data) => {
          //   console.log(data);
          // 让商品数据为null让后使用v-if的组件可以重新销毁和创建
          // 为空后再赋值实现重新加载
          goods.value = null;
          // nextTick作用让空生效，然后再赋值
          // 如果没有这个nextTick上面为空还没有生效就被覆盖了
          nextTick(() => {
            goods.value = data.result;
          });
        });
      }
    },
    { immediate: true }
  );
  return goods;
};
</script>

<style scoped lang='less'>
.goods-info {
  min-height: 600px;
  background: #fff;
  display: flex;
  .media {
    width: 580px;
    height: 600px;
    padding: 30px 50px;
  }
  .spec {
    flex: 1;
    padding: 30px 30px 30px 0;
  }
}
.goods-footer {
  display: flex;
  margin-top: 20px;
  .goods-article {
    width: 940px;
    margin-right: 20px;
  }
  .goods-aside {
    width: 280px;
    min-height: 1000px;
  }
}
// .goods-tabs {
//   min-height: 600px;
//   background: #fff;
// }
.goods-warn {
  min-height: 600px;
  background: #fff;
  margin-top: 20px;
}
</style>